import * as path from 'path';
import * as fs from 'fs';
import { execSync } from 'child_process';

export function execFileExists(filePath: string): boolean {
	let exists = true;
	try {
		exists = fs.statSync(filePath).isFile();
		if (exists) {
			fs.accessSync(filePath, fs.constants.F_OK | fs.constants.X_OK);
		}
	} catch (e) {
		exists = false;
	}
	return exists;
}

//检查是否定义了GOROOT
function getGoRoot(): string {
	return process.env["GOROOT"] || "";
}
function getGoPathFromGOROOT(GOROOT: string): string | null {
	if (GOROOT.length > 0) {
		const pathArry = GOROOT.split(path.delimiter);
		for (const p of pathArry) {
			const binpath = path.join(p, 'bin', "go");
			if (execFileExists(binpath)) {
				return binpath;
			}
		}

	}
	return null;
}

function getGoPathFromCustom(): string | null {
	const customPath = ['/usr/bin/go', '/usr/local/go/bin/go', '/usr/local/bin/go', '/usr/lib/go-1.14/bin/go', '/usr/lib/go-1.15/bin/go'];
	for (const p of customPath) {
		if (execFileExists(p)) {
			return p;
		}
	}
	return null;
}


export function getExecGoPath(): string | null {
	const goPathFromGOROOT = getGoPathFromGOROOT(getGoRoot());
	if (goPathFromGOROOT) {
		return goPathFromGOROOT;
	}

	const goPathFromCustom = getGoPathFromCustom();
	if (goPathFromCustom) {
		return goPathFromCustom;
	}
	return null;
}

export function getExecPip3Path(): string | null {
	const cmd = 'which pip3';
	try {
		const stdout = execSync(cmd).toString().trim();
		if (stdout) {
			if (execFileExists(stdout))
				return stdout;
		}
	} catch {
		return null;
	}
	return null;
}
